﻿/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */
import Cookies from 'js-cookie'
import Qs from "qs";
const TokenKey = 'Admin-Token'
// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

// 字符串格式化(%s )
export function sprintf(str) {
	var args = arguments, flag = true, i = 1;
	str = str.replace(/%s/g, function () {
		var arg = args[i++];
		if (typeof arg === 'undefined') {
			flag = false;
			return '';
		}
		return arg;
	});
	return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
	if (!str || str == "undefined" || str == "null") {
		return "";
	}
	return str;
}


//获取token
export function getToken() {
	return Cookies.get(TokenKey)
}

export function setToken(token) {
	return Cookies.set(TokenKey, token)
}

export function removeToken() {
	return Cookies.remove(TokenKey)
}

export const errorCode = {
	'401': '认证失败，无法访问系统资源',
	'403': '当前操作没有权限',
	'404': '访问资源不存在',
	'default': '系统未知错误，请反馈给管理员'
}

function getFileName(disposition) {
  let filename = ''
  let filenameRegex = /Filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
  let matches = filenameRegex.exec(disposition);
  console.log(matches)
  if (matches != null && matches[1]) { 
    filename = decodeURI(matches[1].replace(/['"]/g, ''));
  }
  return filename
}

// 导出文件
export function exportFile(url, params, filename) {
  let param = Qs.stringify(params)
  let sessionID = Cookies.get('token');
  var xmlResquest = new XMLHttpRequest();
  xmlResquest.open("GET", url + `?${param}`, true);
  xmlResquest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlResquest.setRequestHeader("token", sessionID);
  xmlResquest.responseType = "blob";
  xmlResquest.onload = function () {
      const name = getFileName(xmlResquest.getResponseHeader('content-disposition'))
      console.log(name)
      var content = xmlResquest.response;
      var elink = document.createElement('a');
      elink.download = name || filename;
      elink.style.display = 'none';
      var blob = new Blob([content]);
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
  };
  xmlResquest.send();
}
